/**
 * Copyright &copy; 2012-2016 <a href="https://istep.lczyfz.com">Istep</a> All rights reserved.
 */
package com.lczyfz.istep.modules.resource.web;

import com.lczyfz.istep.common.config.Global;
import com.lczyfz.istep.common.constants.ResourceConstants;
import com.lczyfz.istep.common.constants.SceneConstants;
import com.lczyfz.istep.common.persistence.Page;
import com.lczyfz.istep.common.service.FileUploadService;
import com.lczyfz.istep.common.utils.FormatHtmlUtil;
import com.lczyfz.istep.common.utils.JsonModel;
import com.lczyfz.istep.common.utils.StringUtils;
import com.lczyfz.istep.common.utils.SysUploadUtils;
import com.lczyfz.istep.common.web.BaseController;
import com.lczyfz.istep.modules.resource.entity.ResourceCtfSubject;
import com.lczyfz.istep.modules.resource.entity.ResourceCtfSubjectType;
import com.lczyfz.istep.modules.resource.entity.ResourceFile;
import com.lczyfz.istep.modules.resource.service.ResourceCtfSubjectService;
import com.lczyfz.istep.modules.resource.service.ResourceCtfSubjectTypeService;
import com.lczyfz.istep.modules.resource.service.ResourceFileService;
import com.lczyfz.istep.modules.scene.entity.SceneCtfEnvironment;
import com.lczyfz.istep.modules.scene.entity.SceneCtfEnvironmentInstance;
import com.lczyfz.istep.modules.scene.service.SceneCtfEnvironmentInstanceService;
import com.lczyfz.istep.modules.scene.service.SceneCtfEnvironmentService;
import com.lczyfz.istep.modules.sys.entity.ScheduleJob;
import com.lczyfz.istep.modules.sys.entity.User;
import com.lczyfz.istep.modules.sys.service.ScheduleJobService;
import com.lczyfz.istep.modules.sys.service.SystemService;
import com.lczyfz.istep.modules.sys.utils.UserUtils;
import com.lczyfz.istep.modules.teach.entity.TeachStudentCtfsubject;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * CTF题目管理Controller
 * @author dh
 * @version 2017-01-16
 */
@Controller
@RequestMapping(value = "${adminPath}/resource/resourceCtfSubject")
public class  ResourceCtfSubjectController extends BaseController {
//fds
	@Autowired
	private ResourceCtfSubjectService resourceCtfSubjectService;
	@Autowired
	private ResourceCtfSubjectTypeService resourceCtfSubjectTypeService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private FileUploadService fileUploadService;
	@Autowired
	private ResourceFileService resourceFileService;
	@Autowired
	private SceneCtfEnvironmentService sceneCtfEnvironmentService;
	@Autowired
	private SceneCtfEnvironmentInstanceService sceneCtfEnvironmentInstanceService;
	@Autowired
	private ScheduleJobService scheduleJobService;
	@ModelAttribute
	public ResourceCtfSubject get(@RequestParam(required=false) String id) {
		ResourceCtfSubject entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = resourceCtfSubjectService.get(id);
		}
		if (entity == null){
			entity = new ResourceCtfSubject();
		}
		return entity;
	}

	@RequiresPermissions("resource:resourceCtfSubject:view")
	@RequestMapping(value = {"list", ""})
	public String list(ResourceCtfSubject resourceCtfSubject, HttpServletRequest request, HttpServletResponse response, Model model) {
		if(systemService.isSuperAdmin())
		{
			model.addAttribute("isSuperAdmin", "true");
		}
		else
		{
			model.addAttribute("isSuperAdmin", "false");
		}
		Page<ResourceCtfSubject> page = resourceCtfSubjectService.findPage(new Page<ResourceCtfSubject>(request, response), resourceCtfSubject);
		List<ResourceCtfSubjectType> ctfSubjectTypeList=resourceCtfSubjectTypeService.findList(new ResourceCtfSubjectType());
		model.addAttribute("ctfSubjectTypeList", ctfSubjectTypeList);
		model.addAttribute("page", page);
		return "modules/resource/resourceCtfSubjectList";
	}

	@RequiresPermissions("resource:resourceCtfSubject:view")
	@RequestMapping(value = "form")
	public String form(ResourceCtfSubject resourceCtfSubject, Model model) {
		if(systemService.isSuperAdmin())
		{
			model.addAttribute("isSuperAdmin", "true");
		}else
			model.addAttribute("isSuperAdmin", "false");
		logger.debug("getCtfSubjectTypeId==" + resourceCtfSubject.getCtfSubjectTypeId());
		SceneCtfEnvironment sceneCtfEnvironment=new SceneCtfEnvironment();
		List<SceneCtfEnvironment> sceneCtfEnvironmentList= sceneCtfEnvironmentService.findList(sceneCtfEnvironment);
		List<ResourceCtfSubjectType> ctfSubjectTypeList=resourceCtfSubjectTypeService.findList(new ResourceCtfSubjectType());
		model.addAttribute("ctfSubjectTypeList", ctfSubjectTypeList);
		model.addAttribute("resourceCtfSubject", resourceCtfSubject);
		model.addAttribute("sceneCtfEnvironmentList", sceneCtfEnvironmentList);
		logger.debug("sceneCtfEnvironmentList==" + sceneCtfEnvironmentList.size());

		return "modules/resource/resourceCtfSubjectForm";
	}

	@RequiresPermissions("resource:resourceCtfSubject:edit")
	@RequestMapping(value = "save")
	public String save(ResourceCtfSubject resourceCtfSubject, Model model, RedirectAttributes redirectAttributes,@RequestParam(required = false)String solutionId,@RequestParam(required = false)String attachmentId) throws Exception{
		if (!beanValidator(model, resourceCtfSubject)){
			return form(resourceCtfSubject, model);
		}
		if(resourceCtfSubjectService.get(resourceCtfSubject)==null)
		{
			ResourceCtfSubject temp=resourceCtfSubjectService.findCtfSubjectByName(resourceCtfSubject);
			if(temp != null &&temp.getCtfSubjectName().equals(resourceCtfSubject.getCtfSubjectName()))
			{
				addMessage(redirectAttributes, "保存CTF题目管理失败，改CTF题目已存在");
				return "redirect:"+Global.getAdminPath()+"/resource/resourceCtfSubject/?repage";

			}
		}else{
			ResourceCtfSubject temp=resourceCtfSubjectService.findCtfSubjectByName(resourceCtfSubject);
			if(temp!=null&&!temp.getId().equals(resourceCtfSubject.getId()))
			{
				addMessage(redirectAttributes, "修改CTF题目管理失败，改CTF题目已存在");
				return "redirect:"+Global.getAdminPath()+"/resource/resourceCtfSubject/?repage";
			}

		}

		resourceCtfSubjectService.save(resourceCtfSubject);
		ResourceFile temp1=new ResourceFile();

		if(solutionId!=null&&!solutionId.equals(""))
		{
			logger.debug("solutionId==" + solutionId);
			if(resourceCtfSubjectService.get(resourceCtfSubject) != null)
			{
				temp1.setResourceId(resourceCtfSubject.getId());
				temp1.setType(ResourceConstants.fileTypeSolution);
				List<ResourceFile> list= resourceFileService.findList(temp1);
				for(int i=0;i<list.size();i++)
				{
					if(!list.get(i).getId().equals(solutionId)) {
						resourceFileService.delete(list.get(i));
						File file=new File(list.get(i).getLocalUrl());
						if(file.exists()) {
							file.delete();
							logger.debug("删除文件：[{}]", list.get(i).getLocalUrl());
						}
					}
				}
			}
			ResourceFile resourceFile=resourceFileService.get(solutionId);
			resourceFile.setResourceId(resourceCtfSubject.getId());
			resourceFileService.save(resourceFile);
		}
		if(attachmentId!=null&&!attachmentId.equals(""))
		{
			if(resourceCtfSubjectService.get(resourceCtfSubject) != null)
			{
				temp1.setResourceId(resourceCtfSubject.getId());
				temp1.setType(ResourceConstants.fileTypeAttachment);
				List<ResourceFile> list= resourceFileService.findList(temp1);
				for(int i=0;i<list.size();i++)
				{
					if(!list.get(i).getId().equals(attachmentId)) {
						resourceFileService.delete(list.get(i));
						File file=new File(list.get(i).getLocalUrl());
						if(file.exists()) {
							file.delete();
							logger.debug("删除文件：[{}]", list.get(i).getLocalUrl());
						}
					}
				}
			}
			logger.debug("attachmentId=="+attachmentId);
			ResourceFile resourceFile=resourceFileService.get(attachmentId);
			resourceFile.setResourceId(resourceCtfSubject.getId());
			resourceFileService.save(resourceFile);

		}
		if(resourceCtfSubject.getCtfEnvironmentId()!=null&&!resourceCtfSubject.getCtfEnvironmentId().equals(""))
		{


			SceneCtfEnvironment sceneCtfEnvironment=sceneCtfEnvironmentService.get(resourceCtfSubject.getCtfEnvironmentId());
			if(sceneCtfEnvironment.getCtfType().equals("1"))
			{

				//线程创建实例内部类
				class InstanceThread extends Thread{
					private SceneCtfEnvironment sceneCtfEnvironment;
					private ResourceCtfSubject resourceCtfSubject;

					public InstanceThread(SceneCtfEnvironment sceneCtfEnvironment,ResourceCtfSubject resourceCtfSubject) {

						this.sceneCtfEnvironment=sceneCtfEnvironment;
						this.resourceCtfSubject=resourceCtfSubject;

					}

					public void run(){
						logger.debug("dingh===线程创建实例");

						try {
							SceneCtfEnvironmentInstance sceneCtfEnvironmentInstance=new SceneCtfEnvironmentInstance();
							sceneCtfEnvironmentInstance.setAutoDelete(SceneConstants.AUTO_DELETE_NO);
							sceneCtfEnvironmentService.createCtfInstance(sceneCtfEnvironment, sceneCtfEnvironmentInstance);
							resourceCtfSubject.setInstanceId(sceneCtfEnvironmentInstance.getId());
							resourceCtfSubject.setPort(sceneCtfEnvironment.getPort());
							resourceCtfSubject.setIp(sceneCtfEnvironment.getIp());
							resourceCtfSubjectService.save(resourceCtfSubject);
						} catch (Exception e) {
							e.printStackTrace();
						}


					}
				}
				Thread t1 = new InstanceThread(sceneCtfEnvironment,resourceCtfSubject);
//		t1.start();
				ExecutorService pool= Executors.newCachedThreadPool();
//向线程池中提交两个线程
				pool.submit(t1);
//关闭线程池
				pool.shutdown();







			}
		}
		addMessage(redirectAttributes, "保存CTF题目管理成功");
		return "redirect:"+Global.getAdminPath()+"/resource/resourceCtfSubject/?repage";
	}

	@RequiresPermissions("resource:resourceCtfSubject:view")
	@RequestMapping(value = "findPageByCtfSetId")
	public String findPageByCtfSetId(ResourceCtfSubject resourceCtfSubject, HttpServletRequest request, HttpServletResponse response, Model model) {
		logger.debug("courseId=== [{}]", resourceCtfSubject.getCtfSetId());
		Page<ResourceCtfSubject> page = resourceCtfSubjectService.findPageByCtfSetId(new Page<ResourceCtfSubject>(request, response), resourceCtfSubject);
		logger.debug("page.getList().size()=== [{}]", page.getList().size());
		model.addAttribute("page", page);
		return "modules/resource/resourceCtfSubjectList";
	}

	@RequiresPermissions("resource:resourceCtfSubject:edit")
	@RequestMapping(value = "delete")
	public String delete(ResourceCtfSubject resourceCtfSubject, RedirectAttributes redirectAttributes) throws Exception{

		if(resourceCtfSubject.getInstanceId()!=null&&!resourceCtfSubject.getInstanceId().equals(""))
		{
			logger.debug("dingh==删除实例==");

			SceneCtfEnvironmentInstance sceneCtfEnvironmentInstance=sceneCtfEnvironmentInstanceService.get(resourceCtfSubject.getInstanceId());
			sceneCtfEnvironmentInstanceService.deleteInstance(sceneCtfEnvironmentInstance);
		}
		resourceCtfSubjectService.delete(resourceCtfSubject);
		addMessage(redirectAttributes, "删除CTF题目成功");
		return "redirect:"+Global.getAdminPath()+"/resource/resourceCtfSubject/?repage";
	}

	//CTF题目集链接查看题目
	@RequestMapping(value = "viewCtfSubjectList")
	public String viewCtfSubjectList(HttpServletRequest request, HttpServletResponse response, ResourceCtfSubject resourceCtfSubject, Model model, String ctfSetId) {
		logger.debug("==Evan==viewCtfSubjectList1=="+ctfSetId);
		logger.debug("==Evan==viewCtfSubjectList2=="+resourceCtfSubject.getCtfSubjectName());
//		logger.debug("==Evan==viewCtfSubjectList数据类型=="+ctfSetId.subSequence(0,1));
//		resourceCtfSubject.setCtfSetId((String) ctfSetId.subSequence(0, 1));
		resourceCtfSubject.setCtfSetId(ctfSetId);
		Page<ResourceCtfSubject> page = resourceCtfSubjectService.viewCtfSubjectList(new Page<ResourceCtfSubject>(request, response), resourceCtfSubject);
		model.addAttribute("page", page);
		return "modules/teach/teachViewCtfSubjectList";
	}

	//我的CTF题目集-进入题目集
	@RequestMapping(value = {"stuEnterCtfSetList"})
	public String stuEnterCtfSetList(ResourceCtfSubject resourceCtfSubject, HttpServletRequest request, HttpServletResponse response, Model model) {
		resourceCtfSubject.setCtfSetId(request.getParameter("ctfSetId"));
		logger.debug("==Evan==getCtfSetId==" + resourceCtfSubject.getCtfSetId());

		Page<ResourceCtfSubject> page = resourceCtfSubjectService.stuEnterCtfSetList(new Page<ResourceCtfSubject>(request, response), resourceCtfSubject);
		//列表中展示题目类型，将关联表中的SubjectTypeName设进CtfSubjectTypeId中
		logger.debug("==Evan==size=="+page.getList().size());

		for(int i=0; i<page.getList().size(); i++){

			ResourceCtfSubjectType resourceCtfSubjectType = resourceCtfSubjectTypeService.get(page.getList().get(i).getCtfSubjectTypeId());
			page.getList().get(i).setCtfSubjectTypeId(resourceCtfSubjectType.getSubjectTypeName());
		}
		model.addAttribute("ctfSetId", request.getParameter("ctfSetId"));

		model.addAttribute("page", page);
		return "modules/teach/stuEnterCtfSetList";
	}

	//我的CTF题目集-进入题目集-进入题目
	@RequestMapping(value = "stuEnterCtfSubjectForm")
	public String stuEnterCtfSubjectForm(HttpServletRequest request, HttpServletResponse response, Model model){
		ResourceCtfSubject resourceCtfSubject = resourceCtfSubjectService.get(request.getParameter("CtfSubjectId"));
		//进入题目中展示题目类型，将关联表中的SubjectTypeName设进CtfSubjectTypeId中
		resourceCtfSubject.setCtfSubjectTypeId(resourceCtfSubjectTypeService.get(resourceCtfSubject.getCtfSubjectTypeId()).getSubjectTypeName());
		resourceCtfSubject.setStem(FormatHtmlUtil.formatHtml(StringEscapeUtils.unescapeHtml4(resourceCtfSubject.getStem())));


		TeachStudentCtfsubject temp=new TeachStudentCtfsubject();

		User user = UserUtils.getUser();
		temp.setUserId(user.getId());
		temp.setCtfsubjectId(request.getParameter("CtfSubjectId"));
		TeachStudentCtfsubject result=resourceCtfSubjectService.findStudentCtfSubject(temp);
		if(result!=null)
			model.addAttribute("isAnswered", "true");
		else
			model.addAttribute("isAnswered", "false");
		if(resourceCtfSubject.getCtfEnvironmentId()!=null&&!resourceCtfSubject.getCtfEnvironmentId().equals(""))
		{
			SceneCtfEnvironment sceneCtfEnvironment=sceneCtfEnvironmentService.get(resourceCtfSubject.getCtfEnvironmentId());
			if(sceneCtfEnvironment.getIncreaseTimeAllow().equals("0"))
			{
				model.addAttribute("increaseTime", String.valueOf(Double.parseDouble(sceneCtfEnvironment.getIncreaseTime())*60));

				model.addAttribute("increaseNumber", sceneCtfEnvironment.getIncreaseNumber());
			}


			if(sceneCtfEnvironment.getCtfType().equals("1"))
			{
				String tip=sceneCtfEnvironment.getIp()+" "+sceneCtfEnvironment.getPort();
				model.addAttribute("tip", tip);
			}else {
				String time=String.valueOf(Double.parseDouble(sceneCtfEnvironment.getCtfEnvironmentTime())*3600);
				model.addAttribute("time", time);

				logger.debug("==Evan==time==" + time);

			}

		}


		model.addAttribute("ctfSetId", request.getParameter("ctfSetId"));
		model.addAttribute("resourceCtfSubject", resourceCtfSubject);
		return "modules/teach/stuEnterCtfSubjectForm";
	}
	//竞赛-进入题目
	@RequestMapping(value = "raceEnterCtfSubjectForm")
	public String raceEnterCtfSubjectForm(HttpServletRequest request, HttpServletResponse response, Model model){
		ResourceCtfSubject resourceCtfSubject = resourceCtfSubjectService.get(request.getParameter("CtfSubjectId"));
		//进入题目中展示题目类型，将关联表中的SubjectTypeName设进CtfSubjectTypeId中
		resourceCtfSubject.setCtfSubjectTypeId(resourceCtfSubjectTypeService.get(resourceCtfSubject.getCtfSubjectTypeId()).getSubjectTypeName());
		resourceCtfSubject.setStem(FormatHtmlUtil.formatHtml(StringEscapeUtils.unescapeHtml4(resourceCtfSubject.getStem())));

		TeachStudentCtfsubject temp=new TeachStudentCtfsubject();

		User user = UserUtils.getUser();
		temp.setUserId(user.getId());
		temp.setCtfsubjectId(request.getParameter("CtfSubjectId"));
		TeachStudentCtfsubject result=resourceCtfSubjectService.findStudentCtfSubject(temp);
		if(result!=null)
			model.addAttribute("isAnswered", "true");
		else
			model.addAttribute("isAnswered", "false");
		if(resourceCtfSubject.getCtfEnvironmentId()!=null&&!resourceCtfSubject.getCtfEnvironmentId().equals(""))
		{
			SceneCtfEnvironment sceneCtfEnvironment=sceneCtfEnvironmentService.get(resourceCtfSubject.getCtfEnvironmentId());
			if(sceneCtfEnvironment.getCtfType().equals("1"))
			{
				String tip=sceneCtfEnvironment.getIp()+" "+sceneCtfEnvironment.getPort();
				model.addAttribute("tip", tip);
			}

		}
		model.addAttribute("judge", request.getParameter("judge"));
		model.addAttribute("user", request.getParameter("user"));
		model.addAttribute("paw", request.getParameter("paw"));
		model.addAttribute("repertoryId", request.getParameter("repertoryId"));
		model.addAttribute("scheduleId", request.getParameter("scheduleId"));
		model.addAttribute("userId", request.getParameter("userId"));
		model.addAttribute("subjectId", request.getParameter("subjectId"));
		model.addAttribute("resourceCtfSubject", resourceCtfSubject);
		return "modules/race/raceEnterCtfSubjectForm";
	}

	//查询题目类型列表
	@RequiresPermissions("resource:resourceCtfSubject:view")
	@RequestMapping(value = "subjectTypeList")
	public String subjectTypeList(ResourceCtfSubjectType resourceCtfSubjectType, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ResourceCtfSubjectType> page = resourceCtfSubjectTypeService.findPage(new Page<ResourceCtfSubjectType>(request, response), resourceCtfSubjectType);
		model.addAttribute("resourceCtfSubjectType", resourceCtfSubjectType);
		model.addAttribute("page", page);
		return "modules/resource/resourceCtfSubjectType";
	}
	//删除题目类型
	@RequiresPermissions("resource:resourceCtfSubject:edit")
	@RequestMapping(value = "subjectTypeDelete")
	public String subjectTypeDelete(ResourceCtfSubjectType resourceCtfSubjectType, RedirectAttributes redirectAttributes) {
		logger.debug("删除题目类型");
		resourceCtfSubjectTypeService.delete(resourceCtfSubjectType);
		addMessage(redirectAttributes, "删除题目类型成功");
		return "redirect:"+Global.getAdminPath()+"/resource/resourceCtfSubject/subjectTypeList?repage";
	}

	//
	@RequiresPermissions("resource:resourceCtfSubject:edit")
	@RequestMapping(value = "subjectTypeSave")
	public String subjectTypeSave(ResourceCtfSubjectType resourceCtfSubjectType, Model model, RedirectAttributes redirectAttributes) {

		List<ResourceCtfSubjectType> list=resourceCtfSubjectTypeService.findList(resourceCtfSubjectType);
		if(list!=null&&list.size()>0)
		{

			addMessage(redirectAttributes, "保存题目类型失败，该题目类型已存在");
		}else {
			resourceCtfSubjectTypeService.save(resourceCtfSubjectType);
			addMessage(redirectAttributes, "保存题目类型成功");
		}

		return "redirect:"+Global.getAdminPath()+"/resource/resourceCtfSubject/subjectTypeList?repage";
	}
	//attachmentUpload

	/**
	 * 附件上传
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequiresPermissions("resource:resourceCtfSubject:edit")
	@ResponseBody
	@RequestMapping(value = "attachmentUpload")
	public JsonModel attachmentUpload( HttpServletRequest request) throws IOException {
		logger.debug("开始上传附件");

		JsonModel jsonModel = new JsonModel();
		SysUploadUtils sysUploadUtils=new SysUploadUtils();
		ResourceFile resourceFile=null;
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (multipartResolver.isMultipart(request)) {
			//将request变成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			//获取multiRequest 中所有的文件名
			Iterator iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				//一次遍历所有文件
				MultipartFile file = multiRequest.getFile(iter.next().toString());
				if (file != null) {
					logger.debug("上传===");
					resourceFile=sysUploadUtils.saveFile(file,ResourceConstants.fileTypeAttachment);
				}
			}
		}
		logger.debug("上传==="+sysUploadUtils.getMessage());

		if(resourceFile!=null&&sysUploadUtils.isSuccess())
		{
			resourceFile.setType(ResourceConstants.fileTypeAttachment);// 文件类型：0：视频素材；1：文档素材；2附件
			resourceFileService.save(resourceFile);
			List<String> fileInfo=new ArrayList<>();
			fileInfo.add(resourceFile.getId());
			fileInfo.add(resourceFile.getUrl());
			jsonModel.setSuccess(true);
			jsonModel.setMsg(sysUploadUtils.getMessage());

			jsonModel.setDataObj(fileInfo);
			return jsonModel;
		}else {
			jsonModel.setMsg(sysUploadUtils.getMessage());
			jsonModel.setSuccess(false);
			return jsonModel;
		}



	}
	//上传到ftp
//	public JsonModel attachmentUpload(RedirectAttributes redirectAttributes, HttpServletRequest request, Model model) throws IOException {
//		logger.debug("开始上传附件");
//
//		JsonModel jsonModel = new JsonModel();
//		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
//				request.getSession().getServletContext());
//		//检查form中是否有enctype="multipart/form-data"
//		if (multipartResolver.isMultipart(request)) {
//			//将request变成多部分request
//			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
//			//获取multiRequest 中所有的文件名
//			Iterator iter = multiRequest.getFileNames();
//			while (iter.hasNext()) {
//				//一次遍历所有文件
//				MultipartFile file = multiRequest.getFile(iter.next().toString());
//				if (file != null) {
//					logger.debug("file=========="+file.getOriginalFilename());
//					String OriginalFilename = file.getOriginalFilename();
//					String path = ResourceConstants.resourcePath;
//					Map<String, Object> result= fileUploadService.uploadFile(path,OriginalFilename, file);
//					boolean isSuccess=false;
//					if(result!=null)
//					{
//						isSuccess= (boolean) result.get("isSuccess");
//					}
//
//					if(isSuccess)
//					{
//						String ftpFileAddress= (String) result.get("ftpFileAddress");
//						ResourceFile resourceFile =new ResourceFile();
//						resourceFile.setFileName(OriginalFilename);
//						resourceFile.setFileType(ResourceConstants.fileTypeAttachment);// 文件类型：0：视频素材；1：文档素材；2附件
//						resourceFile.setFtpAddress(ftpFileAddress);
//						logger.debug("ftpFileAddress：[{}]", ftpFileAddress);
//
//						resourceFileService.save(resourceFile);
//						logger.debug("fileInfo：[{}]", resourceFile.getId());
//
//
//						List<String> fileInfo=new ArrayList<>();
//						fileInfo.add(resourceFile.getId());
//						fileInfo.add(ftpFileAddress);
//						jsonModel.setSuccess(true);
//						jsonModel.setDataObj(fileInfo);
//						return jsonModel;
//
//					}
//				}
//			}
//		}
//		jsonModel.setSuccess(false);
//		return jsonModel;
//	}
	/**
	 * 解题思路pdf文件上传
	 * @param redirectAttributes
	 * @param request
	 * @param model
	 * @return
	 * @throws IOException
	 */
	@RequiresPermissions("resource:resourceCtfSubject:edit")
	@ResponseBody
	@RequestMapping(value = "solutionUpload")
	public JsonModel solutionUpload(RedirectAttributes redirectAttributes, HttpServletRequest request, Model model) throws IOException {
		logger.debug("开始上传解题思路pdf");

		JsonModel jsonModel = new JsonModel();
		SysUploadUtils sysUploadUtils=new SysUploadUtils();
//		ResourceFile file=sysUploadUtils.uploadFile(request,ResourceConstants.fileTypeSolution);
		ResourceFile resourceFile=null;
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (multipartResolver.isMultipart(request)) {
			//将request变成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			//获取multiRequest 中所有的文件名
			Iterator iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				//一次遍历所有文件
				MultipartFile file = multiRequest.getFile(iter.next().toString());
				if (file != null) {
					logger.debug("上传===");
					resourceFile=sysUploadUtils.saveFile(file,ResourceConstants.fileTypeSolution);
				}
			}
		}
		logger.debug("上传Message==="+sysUploadUtils.getMessage());

		if(resourceFile!=null&&sysUploadUtils.isSuccess())
		{
			logger.debug("上传成功");

			resourceFile.setType(ResourceConstants.fileTypeSolution);// 文件类型：0：视频素材；1：文档素材；2附件,3文档素材
			resourceFileService.save(resourceFile);
			List<String> fileInfo=new ArrayList<>();
			fileInfo.add(resourceFile.getId());
			fileInfo.add(resourceFile.getUrl());
			jsonModel.setSuccess(true);
			jsonModel.setMsg(sysUploadUtils.getMessage());

			jsonModel.setDataObj(fileInfo);


			return jsonModel;
		}else {
			jsonModel.setMsg(sysUploadUtils.getMessage());

			jsonModel.setSuccess(false);
			return jsonModel;
		}
	}



	@RequiresPermissions("resource:resourceCtfSubject:edit")
	@RequestMapping(value = "detail")
	public String detail(ResourceCtfSubject resourceCtfSubject, Model model, HttpServletRequest request, HttpServletResponse response) {

//		ResourceQuestion resourceQuestion=new ResourceQuestion();
//		resourceQuestion.setPaperId(resourcePaper.getId());
//
//		Page<ResourceQuestion> page = resourceQuestionService.findPageByPaperId(new Page<ResourceQuestion>(request, response), resourceQuestion);
//		model.addAttribute("page", page);
//		model.addAttribute("resourceQuestion", resourceQuestion);

		return "modules/resource/resourceCtfSubjectDetail";
	}

	/**
	 * 保存用户做的ctf题目答案
	 */
	@ResponseBody
	@RequestMapping(value = "saveAnswer")
	public String saveAnswer(@RequestParam(required = false) String answer,@RequestParam(required = false) String ctfsubjectId) {

		logger.debug("dingh===" + answer + " " + ctfsubjectId);
		TeachStudentCtfsubject teachStudentCtfsubject=new TeachStudentCtfsubject();
		teachStudentCtfsubject.setAnswer(answer);
		teachStudentCtfsubject.setCtfsubjectId(ctfsubjectId);
		User user = UserUtils.getUser();
		TeachStudentCtfsubject temp=new TeachStudentCtfsubject();
		temp.setUserId(user.getId());
		temp.setCtfsubjectId(ctfsubjectId);

		TeachStudentCtfsubject result=resourceCtfSubjectService.findStudentCtfSubject(temp);
		if(result!=null&&!result.equals(""))
		{
			logger.debug("dingh===更新=");

			result.setAnswer(answer);
			Date date=new Date();
			result.setUpdateBy(user);
			result.setUpdateDate(date);
			resourceCtfSubjectService.updateAnswer(result);
		}else {
			logger.debug("dingh===插入=");
			resourceCtfSubjectService.saveAnswer(teachStudentCtfsubject);
		}
		return null;

	}
	/**
	 * 增加ctf实验时间
	 */
	@ResponseBody
	@RequestMapping(value = "addTime")
	public String addTime(@RequestParam(required = false) String ctfEnvironmentId,@RequestParam(required = false) String instanceId) {

		logger.debug("dingh===" + ctfEnvironmentId + " " + instanceId);
		SceneCtfEnvironmentInstance sceneCtfEnvironmentInstance=sceneCtfEnvironmentInstanceService.get(instanceId);
		SceneCtfEnvironment sceneCtfEnvironment=sceneCtfEnvironmentService.get(ctfEnvironmentId);

		Date data=sceneCtfEnvironmentInstance.getEndDate();
		int envTime=(int)(Double.parseDouble(sceneCtfEnvironment.getIncreaseTime())*60);
		Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
		ca.setTime(data); //设置时间为当前时间
		ca.set(Calendar.MINUTE, ca.get(Calendar.MINUTE) + envTime);
		Date endDate=ca.getTime();
		sceneCtfEnvironmentInstance.setEndDate(endDate);

		ScheduleJob scheduleJob= scheduleJobService.findByJobName("env_instance", instanceId);
		scheduleJob.setStartDate(endDate);
		scheduleJob.setCronExpression(getCancelTime(data, envTime));

		scheduleJobService.save(scheduleJob);
		sceneCtfEnvironmentInstanceService.save(sceneCtfEnvironmentInstance);

		logger.debug("dingh===endDate=" + endDate);
		logger.debug("dingh===getCancelTime=" + getCancelTime(data, envTime));


		ca.setTime(endDate); //设置时间为当前时间
		int year = ca.get(Calendar.YEAR);//获取年份
		int month=ca.get(Calendar.MONTH)+1;//获取月份
		int day=ca.get(Calendar.DATE);//获取日
		int hour=ca.get(Calendar.HOUR_OF_DAY);//小时
		int minute=ca.get(Calendar.MINUTE);//分
		int second=ca.get(Calendar.SECOND);//秒    2017/05/16 20:27:30
		//"30 10 1 20 10 ? 2011" 2011年10月20号1点10分30秒触发任务
		String endTime=year+"/"+month+"/"+day+" "+hour+":"+minute+":"+second;


		logger.debug("dingh===endTime=" + endTime);

		return endTime;

	}

	/**
	 * 保存用户做的ctf题目答案
	 */
	@ResponseBody
	@RequestMapping(value = "saveRaceAnswer")
	public String saveRaceAnswer(@RequestParam(required = false) String answer, @RequestParam(required = false) String ctfsubjectId) {

		logger.debug("dingh===" + answer + " " + ctfsubjectId);
		TeachStudentCtfsubject teachStudentCtfsubject = new TeachStudentCtfsubject();
		teachStudentCtfsubject.setAnswer(answer);
		teachStudentCtfsubject.setCtfsubjectId(ctfsubjectId);
		User user = UserUtils.getUser();
		TeachStudentCtfsubject temp = new TeachStudentCtfsubject();
		temp.setUserId(user.getId());
		temp.setCtfsubjectId(ctfsubjectId);

		TeachStudentCtfsubject result = resourceCtfSubjectService.findStudentCtfSubject(temp);
		if (result != null && !result.equals("")) {
			logger.debug("dingh===更新=");

			result.setAnswer(answer);
			Date date = new Date();
			result.setUpdateBy(user);
			result.setUpdateDate(date);
			resourceCtfSubjectService.updateAnswer(result);
		} else {
			logger.debug("dingh===插入=");
			resourceCtfSubjectService.saveAnswer(teachStudentCtfsubject);
		}
		//补充，，，


		return null;

	}
	//下载附件   调用浏览器各自的下载方式
	@RequestMapping(value = "downloadDocFiles")
	public String downloadDocFiles(String ctfSubjectId, HttpServletResponse response) throws IOException, URISyntaxException {
		logger.debug("dingh===ctfSubjectId="+ctfSubjectId);

		ArrayList<ResourceFile> totalFileList = new ArrayList<>();
		//循环该课程下所有课件
		ResourceFile resourceFile = new ResourceFile();
		resourceFile.setResourceId(ctfSubjectId);
		resourceFile.setType(ResourceConstants.fileTypeAttachment);
		List<ResourceFile> fileList = resourceFileService.findList(resourceFile);
		//循环所有课件下的所有文档
		for (ResourceFile aFileList : fileList) {
			logger.debug("==Evan==aFileList" + aFileList);
			totalFileList.add(aFileList);
		}
		logger.debug("==Evan==totalFileNum: " + totalFileList.size());

		response.setCharacterEncoding("utf-8");
		response.setContentType("APPLICATION/OCTET-STREAM");
		//设置content-disposition响应头控制浏览器以下载的形式打开文件，中文文件名要使用URLEncoder.encode方法进行编码，否则会出现文件名乱码
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
//		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode( "课程文档" + sdf.format(new Date()) + ".zip", "UTF-8"));
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(resourceCtfSubjectService.get(ctfSubjectId).getCtfSubjectName() + "_附件" + ".zip", "UTF-8"));
		//创建输出流
		OutputStream os = response.getOutputStream();
		byte[] buf = new byte[1024];
		try {
			//ZipOutputStream类：完成文件或文件夹的压缩
			ZipOutputStream out = new ZipOutputStream(os);
			for (ResourceFile aTotalFileList : totalFileList) {
				FileInputStream fis = new FileInputStream(aTotalFileList.getLocalUrl());
				out.putNextEntry(new ZipEntry(aTotalFileList.getName()));
				int len;
				while ((len = fis.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
				out.closeEntry();
				fis.close();
			}
			out.flush();
			out.close();
			logger.debug("Evan========压缩完成!!!");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 创建ctf实例
	 * @param ctfEnvironmentId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "createCtfInstance")
	public List<String> createCtfInstance(@RequestParam(required = false) String ctfEnvironmentId) throws Exception{
		logger.debug("createCtfInstance===" + ctfEnvironmentId);

		SceneCtfEnvironmentInstance sceneCtfEnvironmentInstance=new SceneCtfEnvironmentInstance();
		SceneCtfEnvironment sceneCtfEnvironment=sceneCtfEnvironmentService.get(ctfEnvironmentId);
		sceneCtfEnvironmentInstance.setAutoDelete(SceneConstants.AUTO_DELETE_NO);

		sceneCtfEnvironmentService.createCtfInstance(sceneCtfEnvironment, sceneCtfEnvironmentInstance);

		Date orderTime=sceneCtfEnvironmentInstance.getEndDate();
		Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
		ca.setTime(orderTime); //设置时间为当前时间
		int year = ca.get(Calendar.YEAR);//获取年份
		int month=ca.get(Calendar.MONTH)+1;//获取月份
		int day=ca.get(Calendar.DATE);//获取日
		int hour=ca.get(Calendar.HOUR_OF_DAY);//小时
		int minute=ca.get(Calendar.MINUTE);//分
		int second=ca.get(Calendar.SECOND);//秒    2017/05/16 20:27:30
		//"30 10 1 20 10 ? 2011" 2011年10月20号1点10分30秒触发任务
		String endTime=year+"/"+month+"/"+day+" "+hour+":"+minute+":"+second;

		List<String> list=new ArrayList<>();
//		double time=Double.parseDouble(sceneCtfEnvironment.getCtfEnvironmentTime())*60*60;
		String link=sceneCtfEnvironmentInstance.getLink();
		String instanceId=sceneCtfEnvironmentInstance.getId();
		list.add(endTime);
		list.add(link);
		list.add(instanceId);

		logger.debug("dingh========list=" + list.get(0)+" "+list.get(1)+" "+list.get(2));


		return list;
	}

	@RequestMapping(value = "lookSolution")
	public String lookSolution(String ctfSubjectId, Model model, HttpServletRequest request, HttpServletResponse response) {




		return "modules/resource/sceneCtfSubjectSolution";
	}

	/**
	 * 〈方法的功能描述〉:
	 *获取取消订单的定时任务的时间
	 * @Date	 2016/12/6/11:22
	 * @author  dingh
	 * @methodName
	 * @param
	 * @return
	 **/

	public String getCancelTime(Date orderTime,int afterMinute){
		Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
		ca.setTime(orderTime); //设置时间为当前时间
		ca.set(Calendar.MINUTE, ca.get(Calendar.MINUTE) + afterMinute);
		Date time = ca.getTime(); //结果
		int year = ca.get(Calendar.YEAR);//获取年份
		int month=ca.get(Calendar.MONTH)+1;//获取月份
		int day=ca.get(Calendar.DATE);//获取日
		int hour=ca.get(Calendar.HOUR_OF_DAY);//小时
		int minute=ca.get(Calendar.MINUTE);//分
		int second=ca.get(Calendar.SECOND);//秒
		//"30 10 1 20 10 ? 2011" 2011年10月20号1点10分30秒触发任务
		String cancelTime=second+" "+minute+" "+hour+" "+day+" "+month+" "+"? "+year;
		return cancelTime;

	}
	public Date getCancelTimeByDate(Date orderTime,int afterMinute){
		Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
		ca.setTime(orderTime); //设置时间为当前时间
		ca.set(Calendar.MINUTE, ca.get(Calendar.MINUTE) + afterMinute);
//		ca.add(Calendar.SECOND, +30);
		Date time = ca.getTime(); //结果
		return time;
	}

}